package com.doublepointer;

public class Solution07 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = 0;
        int lenB = 0;
        ListNode pA = headA;
        ListNode pB = headB;
        while (pA != null) {
            lenA++;
            pA = pA.next;
        }
        while (pB != null) {
            lenB++;
            pB = pB.next;
        }
        pA = headA;
        pB = headB;
        if (lenB > lenA) {
            lenA ^= lenB;
            lenB ^= lenA;
            lenA ^= lenB;
            ListNode tmp = pA;
            pA = pB;
            pB = tmp;
        }

        int i = lenA-lenB;
        while (i-- >0) {
            pA = pA.next;
        }

        while (pA != null) {
            if (pA == pB) {
                return pA;
            }
            pA = pA.next;
            pB = pB.next;
        }
        return null;
    }
}
